package edu.fight.controller;

import com.alibaba.fastjson.JSONObject;
import edu.fight.dto.Result;
import edu.fight.dto.ResultStatus;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;

@RestController
@RequestMapping("/auth")
@Slf4j
public class LoginController {

    @PostMapping("/login")
    public Result login(@RequestParam String username, @RequestParam String password){
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            Subject subject = SecurityUtils.getSubject();

            subject.login(token);
            Serializable id = subject.getSession().getId();
            return Result.to(ResultStatus.sucess,null,null,id);
        }catch (Exception e){
            e.printStackTrace();
            log.error("登录异常：{}",e.getMessage());

            return Result.to(ResultStatus.error,null,null,e.getMessage());
        }
    }

    @GetMapping("/logout")
    public Result logout(){
        try {
            Subject subject = SecurityUtils.getSubject();
            Object principal = subject.getPrincipal();
            String jsonpricipal = JSONObject.toJSONString(principal);
            System.out.println("+++do logout+++"+jsonpricipal);

            subject.logout();
            return Result.to(ResultStatus.sucess,"退出成功",null,null );
        }catch (Exception e){
            e.printStackTrace();
            log.error("异常：{}",e.getMessage());

            return Result.to(ResultStatus.error,null,null,e.getMessage());
        }
    }
}
